#!/usr/bin/env python
# coding=utf-8
'''
Author: Logan
Date: 2020-11-23 16:28:39
LastEditTime: 2022-11-02 01:17:25
Description: 

Doc: https://www.vultr.com/api/
'''
import requests
import json
import pprint
import time
import sys
import os
import re

# sys.path.append("..")
# from custom_log import log_start
# logger = log_start('vultr')
"""
curl "https://api.vultr.com/v2/plans?vc2=" \
  -X GET \
  -H "Authorization: Bearer CKYT4PAYYZXB67AESUVTLACXTXJ3RY2PJZBQ"

curl "https://api.vultr.com/v2/regions/nrt/availability" \
  -X GET \
  -H "Authorization: Bearer CKYT4PAYYZXB67AESUVTLACXTXJ3RY2PJZBQ"


  
"""


config = {
    "VultrConfig": 'CKYT4PAYYZXB67AESUVTLACXTXJ3RY2PJZBQ',
}

class VultrAPI(object):

    def __init__(self, token):
        self.url = "https://api.vultr.com/v2"
        self.token = token
        self.headers = {
            "Content-Type": "application/json",
            "charset": "UTF-8",
            "Authorization": "Bearer "+self.token
        }
    
    def account(self):
        """
        打印账号信息
        """
        url = "https://api.vultr.com/v2/account"
        print(self.headers)
        response = requests.get(url, headers=self.headers)
        return response.json()


    
    def get_regions(self):
        url = "https://api.vultr.com/v2/regions"
        response = requests.get(url, headers=self.headers)
        regions = response.json()
        data = {}
        if regions:
            for i in regions['regions']:
                data[i['city']]=i['id']
        return data
    def create_instance(self):
        url = "https://api.vultr.com/v2/instances"
        payload = {            
            "region": "nrt",
            "plan": "vc2-1c-1gb",
            "label": "Example Instance",
            "user_data": "QmFzZTY0IEV4YW1wbGUgRGF0YQ==",
            "backups": "enabled",
            "hostname": "my_hostname"
        }
        response = requests.post(url, headers=self.headers,data=json.dumps(payload))
        return response.json()

    

    def get_id_instance_ip(self,instance_ip):
        url = "https://api.vultr.com/v2/instances?main_ip={}".format(instance_ip)
        response = requests.get(url, headers=self.headers)
        instance = response.json()
        if instance:
            return instance['instances'][0]

    def list_instance_all(self, num=100):
        url = "https://api.vultr.com/v2/instances?page=1&per_page={}".format(num)
        response = requests.get(url, headers=self.headers)
        return response.json()



    def powercycle_server(self,instance_ip):
        instance = self.get_id_instance_ip(instance_ip)
        url = "https://api.vultr.com/v2/instances/{}/reboot".format(instance['id'])
        response = requests.post(url, headers=self.headers)
        info = "instance: {} 重启中".format(instance['label'])
        # logger.info(info)
        print(info)
        return response.status_code
    




if __name__ == '__main__':
    token = config['VultrConfig']
    VPSApi = VultrAPI(token)
    
    # 帐号信息
    pprint.pprint(VPSApi.account(), indent=3)
    pprint.pprint(VPSApi.list_instance_all(10), indent=3)
    ret = VPSApi.get_regions()
    print(ret)
    ret = VPSApi.create_instance()
    print(ret)
    # #查看实例　id:39676810
    # pprint.pprint(VPSApi.get_id_instance_id(39676810), indent=3)
    # pprint.pprint(VPSApi.get_id_instance_ip('139.180.168.203'), indent=3)
    # # 重启主机
    # pprint.pprint(VPSApi.powercycle_server('139.180.168.203'), indent=3)